import urllib
import requests
import json
import time
import hashlib

url="https://www.toutiao.com/api/pc/feed/"
#url="https://www.toutiao.com/api/pc/feed/?category=movie&utm_source=toutiao&widen=1&max_behot_time=0&max_behot_time_tmp=0&tadrequire=true&as=A1651D99EAAA321&cp=5D9A7A43C2A16E1&_signature=QuUGwQAAH4GqPyS8b8BMTELlBt"

headers={
    "Cookie":"tt_webid=6744890312793818627",
    "referer": "https://www.toutiao.com/ch/movie/",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
    "x-requested-with": "XMLHttpRequest"
}

def get_data(url,headers,params):
    r = requests.get(url, headers=headers, params=params)
    print(url)
    res = json.loads(r.content)
    return json.loads(r.content)

def get_as_cp():
    zz ={}
    now = round(time.time())
    e = hex(int(now)).upper()[2:]  #hex()转换一个整数对象为十六进制的字符串表示
    hashObj=hashlib.md5()
    hashObj.update(str(int(now)).encode("utf-8"))
    i=hashObj.hexdigest().upper()
    if len(e)!=8:
        zz = {'as': "479BB4B7254C150",
            'cp': "7E0AC8874BB0985"}
        return zz
    n=i[:5]
    a=i[-5:]
    r = ""
    s = ""
    for i in range(5):
        s = s+n[i]+e[i]
    for j in range(5):
        r = r+e[j+3]+a[j]
    zz = {
        'as': "A1" + s + e[-3:],
        'cp': e[0:3] + r + "E1"
    }
    return (zz)

def get_signature(self,user_id):
    return
if __name__=="__main__":
    params = {
        "category": "movie",
        "utm_source": "toutiao",
        "widen": 1,
        "max_behot_time": 0,
        "max_behot_time_tmp": 0,
        "tadrequire": "true",
        "as": get_as_cp()['as'],
        "cp": get_as_cp()['cp'],
        "_signature": "QuUGwQAAH4GqPyS8b8BMTELlBt",
    }
    res=get_data(url,headers,params)
    print(res['next']['max_behot_time'])
    print(res)
    reqtime=str(res['next']['max_behot_time'])
    for index in range(100):
        time.sleep(2)
        newparams = {
            "category": "movie",
            "utm_source": "toutiao",
            "widen": 1,
            "max_behot_time": reqtime,
            "max_behot_time_tmp": reqtime,
            "tadrequire": "true",
            "as": get_as_cp()['as'],
            "cp": get_as_cp()['cp'],
            "_signature": "QuUGwQAAH4GqPyS8b8BMTELlBt",
        }
        data=get_data(url,headers=headers,params=newparams)
        print(data)
    # with open('json.txt','w') as f:
    #     f.write(json.dumps(res))
    # f.close()
